﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace Peer
{
    public abstract class BaseConverter
    {
        private readonly BinaryFormatter binaryFormatter = new BinaryFormatter();

        /// <summary>
        /// 系列化
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public abstract byte[] Serialize(object data);

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public abstract T Deserialize<T>(byte[] bytes);

        /// <summary>
        /// 根据类型反序列化
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public abstract object DeserializeObject(byte[] bytes, Type type);


        public Stream Serialize<S>(S exception) where S : ISerializable
        {
            var stream = new MemoryStream();
            binaryFormatter.Serialize(stream, exception);
            stream.Position = 0;
            return stream;
        }

        public object DeserializeObject(Stream stream)
        {
            using (stream)
            {
                return binaryFormatter.Deserialize(stream);
            }
        }
    }
}
